home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / DistUpgrade / DistUpgradeViewKDE.py < prev    next >
Encoding:
Python Source  |  2009-04-27  |  35.1 KB  |  840 lines

  1. # DistUpgradeViewKDE.py 
  2. #  
  3. #  Copyright (c) 2007 Canonical Ltd
  4. #  
  5. #  Author: Jonathan Riddell <jriddell@ubuntu.com>
  6. #  This program is free software; you can redistribute it and/or 
  7. #  modify it under the terms of the GNU General Public License as 
  8. #  published by the Free Software Foundation; either version 2 of the
  9. #  License, or (at your option) any later version.
  10. #  This program is distributed in the hope that it will be useful,
  11. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #  GNU General Public License for more details.
  14. #  You should have received a copy of the GNU General Public License
  15. #  along with this program; if not, write to the Free Software
  16. #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  17. #  USA
  18.  
  19. from PyQt4.QtCore import *
  20. from PyQt4.QtGui import *
  21. from PyQt4 import uic
  22.  
  23. import sys
  24. import logging
  25. import time
  26. import subprocess
  27. import traceback
  28. import tempfile
  29.  
  30. import apt
  31. import apt_pkg
  32. import os
  33. import shutil
  34.  
  35. import pty
  36.  
  37. from DistUpgradeApport import *
  38.  
  39. from DistUpgradeController import DistUpgradeController
  40. from DistUpgradeView import DistUpgradeView, FuzzyTimeToStr, InstallProgress, FetchProgress
  41.  
  42. import select
  43. import gettext
  44. from DistUpgradeGettext import gettext as gett
  45.  
  46. def _(str):
  47.     return unicode(gett(str), 'UTF-8')
  48.  
  49. def utf8(str):
  50.   if isinstance(str, unicode):
  51.       return str
  52.   return unicode(str, 'UTF-8')
  53.  
  54. def loadUi(file, parent):
  55.     if os.path.exists(file):
  56.         uic.loadUi(file, parent)
  57.     else:
  58.         #FIXME find file
  59.         print "error, can't find file: " + file
  60.  
  61. class DumbTerminal(QTextEdit):
  62.     """ A very dumb terminal """
  63.     def __init__(self, installProgress, parent_frame):
  64.         " really dumb terminal with simple editing support "
  65.         QTextEdit.__init__(self, "", parent_frame)
  66.         self.installProgress = installProgress
  67.         self.setFontFamily("Monospace")
  68.         self.setFontPointSize(8)
  69.         self.setWordWrapMode(QTextOption.NoWrap)
  70.         self.setUndoRedoEnabled(False)
  71.         self.setOverwriteMode(True)
  72.         self._block = False
  73.         #self.connect(self, SIGNAL("cursorPositionChanged()"), 
  74.         #             self.onCursorPositionChanged)
  75.  
  76.     def fork(self):
  77.         """pty voodoo"""
  78.         (self.child_pid, self.installProgress.master_fd) = pty.fork()
  79.         if self.child_pid == 0:
  80.             os.environ["TERM"] = "dumb"
  81.         return self.child_pid
  82.  
  83.     def updateInterface(self):
  84.         (rlist, wlist, xlist) = select.select([self.installProgress.master_fd],[],[], 0)
  85.         if len(rlist) > 0:
  86.             line = os.read(self.installProgress.master_fd, 255)
  87.             self.insertWithTermCodes(utf8(line))
  88.         QApplication.processEvents()
  89.  
  90.     def insertWithTermCodes(self, text):
  91.         """ support basic terminal codes """
  92.         display_text = ""
  93.         for c in text:
  94.             # \b - backspace - this seems to comes as "^H" now ??!
  95.             if ord(c) == 8:
  96.                 self.insertPlainText(display_text)
  97.                 self.textCursor().deletePreviousChar()
  98.                 display_text=""
  99.             # \r - is filtered out
  100.             elif c == chr(13):
  101.                 pass
  102.             # \a - bell - ignore for now
  103.             elif c == chr(7):
  104.                 pass
  105.             else:
  106.                 display_text += c
  107.         self.insertPlainText(display_text)
  108.  
  109.     def keyPressEvent(self, ev):
  110.         """ send (ascii) key events to the pty """
  111.         # no master_fd yet
  112.         if not hasattr(self.installProgress, "master_fd"):
  113.             return
  114.         # special handling for backspace
  115.         if ev.key() == Qt.Key_Backspace:
  116.             #print "sent backspace"
  117.             os.write(self.installProgress.master_fd, chr(8))
  118.             return
  119.         # do nothing for events like "shift" 
  120.         if not ev.text():
  121.             return
  122.         # now sent the key event to the termianl as utf-8
  123.         os.write(self.installProgress.master_fd, ev.text().toUtf8())
  124.  
  125.     def onCursorPositionChanged(self):
  126.         """ helper that ensures that the cursor is always at the end """
  127.         if self._block:
  128.             return
  129.         # block signals so that we do not run into a recursion
  130.         self._block = True
  131.         self.moveCursor(QTextCursor.End)
  132.         self._block = False
  133.  
  134. class KDECdromProgressAdapter(apt.progress.CdromProgress):
  135.     """ Report the cdrom add progress """
  136.     def __init__(self, parent):
  137.         self.status = parent.window_main.label_status
  138.         self.progressbar = parent.window_main.progressbar_cache
  139.         self.parent = parent
  140.  
  141.     def update(self, text, step):
  142.         """ update is called regularly so that the gui can be redrawn """
  143.         if text:
  144.           self.status.setText(text)
  145.         self.progressbar.setValue(step/float(self.totalSteps))
  146.         QApplication.processEvents()
  147.  
  148.     def askCdromName(self):
  149.         return (False, "")
  150.  
  151.     def changeCdrom(self):
  152.         return False
  153.  
  154. class KDEOpProgress(apt.progress.OpProgress):
  155.   """ methods on the progress bar """
  156.   def __init__(self, progressbar, progressbar_label):
  157.       self.progressbar = progressbar
  158.       self.progressbar_label = progressbar_label
  159.       #self.progressbar.set_pulse_step(0.01)
  160.       #self.progressbar.pulse()
  161.  
  162.   def update(self, percent):
  163.       #if percent > 99:
  164.       #    self.progressbar.set_fraction(1)
  165.       #else:
  166.       #    self.progressbar.pulse()
  167.       #self.progressbar.set_fraction(percent/100.0)
  168.       self.progressbar.setValue(percent)
  169.       QApplication.processEvents()
  170.  
  171.   def done(self):
  172.       self.progressbar_label.setText("")
  173.  
  174. class KDEFetchProgressAdapter(FetchProgress):
  175.     """ methods for updating the progress bar while fetching packages """
  176.     # FIXME: we really should have some sort of "we are at step"
  177.     # xy in the gui
  178.     # FIXME2: we need to thing about mediaCheck here too
  179.     def __init__(self, parent):
  180.         FetchProgress.__init__(self)
  181.         # if this is set to false the download will cancel
  182.         self.status = parent.window_main.label_status
  183.         self.progress = parent.window_main.progressbar_cache
  184.         self.parent = parent
  185.  
  186.     def mediaChange(self, medium, drive):
  187.       msg = _("Please insert '%s' into the drive '%s'") % (medium,drive)
  188.       change = QMessageBox.question(self.parent.window_main, _("Media Change"), msg, QMessageBox.Ok, QMessageBox.Cancel)
  189.       if change == QMessageBox.Ok:
  190.         return True
  191.       return False
  192.  
  193.     def start(self):
  194.         #self.progress.show()
  195.         self.progress.setValue(0)
  196.         self.status.show()
  197.  
  198.     def stop(self):
  199.         self.parent.window_main.progress_text.setText("  ")
  200.         self.status.setText(_("Fetching is complete"))
  201.  
  202.     def pulse(self):
  203.         """ we don't have a mainloop in this application, we just call processEvents here and elsewhere"""
  204.         # FIXME: move the status_str and progress_str into python-apt
  205.         # (python-apt need i18n first for this)
  206.         FetchProgress.pulse(self)
  207.         self.progress.setValue(self.percent)
  208.         currentItem = self.currentItems + 1
  209.         if currentItem > self.totalItems:
  210.             currentItem = self.totalItems
  211.  
  212.         if self.currentCPS > 0:
  213.             self.status.setText(_("Fetching file %li of %li at %sB/s") % (currentItem, self.totalItems, apt_pkg.SizeToStr(self.currentCPS)))
  214.             self.parent.window_main.progress_text.setText("<i>" + _("About %s remaining") % unicode(FuzzyTimeToStr(self.eta), 'utf-8') + "</i>")
  215.         else:
  216.             self.status.setText(_("Fetching file %li of %li") % (currentItem, self.totalItems))
  217.             self.parent.window_main.progress_text.setText("  ")
  218.  
  219.         QApplication.processEvents()
  220.         return True
  221.  
  222. class KDEInstallProgressAdapter(InstallProgress):
  223.     """methods for updating the progress bar while installing packages"""
  224.     # timeout with no status change when the terminal is expanded
  225.     # automatically
  226.     TIMEOUT_TERMINAL_ACTIVITY = 240
  227.  
  228.     def __init__(self,parent):
  229.         InstallProgress.__init__(self)
  230.         self._cache = None
  231.         self.label_status = parent.window_main.label_status
  232.         self.progress = parent.window_main.progressbar_cache
  233.         self.progress_text = parent.window_main.progress_text
  234.         self.parent = parent
  235.         try:
  236.             self._terminal_log = open("/var/log/dist-upgrade/term.log","w")
  237.         except Exception, e:
  238.             # if something goes wrong (permission denied etc), use stdout
  239.             logging.error("Can not open terminal log: '%s'" % e)
  240.             self._terminal_log = sys.stdout
  241.         # some options for dpkg to make it die less easily
  242.         apt_pkg.Config.Set("DPkg::StopOnError","False")
  243.  
  244.     def startUpdate(self):
  245.         InstallProgress.startUpdate(self)
  246.         self.finished = False
  247.         # FIXME: add support for the timeout
  248.         # of the terminal (to display something useful then)
  249.         # -> longer term, move this code into python-apt 
  250.         self.label_status.setText(_("Applying changes"))
  251.         self.progress.setValue(0)
  252.         self.progress_text.setText(" ")
  253.         # do a bit of time-keeping
  254.         self.start_time = 0.0
  255.         self.time_ui = 0.0
  256.         self.last_activity = 0.0
  257.         self.parent.window_main.showTerminalButton.setEnabled(True)
  258.  
  259.     def error(self, pkg, errormsg):
  260.         InstallProgress.error(self, pkg, errormsg)
  261.         logging.error("got an error from dpkg for pkg: '%s': '%s'" % (pkg, errormsg))
  262.         # we do not report followup errors from earlier failures
  263.         if gettext.dgettext('dpkg', "dependency problems - leaving unconfigured") in errormsg:
  264.           return False
  265.         summary = _("Could not install '%s'") % pkg
  266.         msg = _("The upgrade will continue but the '%s' package may be "
  267.                 "in a not working state. Please consider submitting a "
  268.                 "bug report about it.") % pkg
  269.         msg = "<big><b>%s</b></big><br />%s" % (summary, msg)
  270.  
  271.         dialogue = QDialog(self.parent.window_main)
  272.         loadUi("dialog_error.ui", dialogue)
  273.         self.parent.translate_widget_children(dialogue)
  274.         dialogue.label_error.setText(utf8(msg))
  275.         if errormsg != None:
  276.             dialogue.textview_error.setText(utf8(errormsg))
  277.             dialogue.textview_error.show()
  278.         else:
  279.             dialogue.textview_error.hide()
  280.         dialogue.connect(dialogue.button_bugreport, SIGNAL("clicked()"), self.parent.reportBug)
  281.         dialogue.exec_()
  282.  
  283.     def conffile(self, current, new):
  284.         """ask question in case conffile has been changed by user"""
  285.         logging.debug("got a conffile-prompt from dpkg for file: '%s'" % current)
  286.         start = time.time()
  287.         prim = _("Replace the customized configuration file\n'%s'?") % current
  288.         sec = _("You will lose any changes you have made to this "
  289.                 "configuration file if you choose to replace it with "
  290.                 "a newer version.")
  291.         markup = "<span weight=\"bold\" size=\"larger\">%s </span> \n\n%s" % (prim, sec)
  292.         self.confDialogue = QDialog(self.parent.window_main)
  293.         loadUi("dialog_conffile.ui", self.confDialogue)
  294.         self.confDialogue.label_conffile.setText(markup)
  295.         self.confDialogue.textview_conffile.hide()
  296.         #FIXME, below to be tested
  297.         #self.confDialogue.resize(self.confDialogue.minimumSizeHint())
  298.         self.confDialogue.connect(self.confDialogue.show_difference_button, SIGNAL("clicked()"), self.showConffile)
  299.  
  300.         # now get the diff
  301.         if os.path.exists("/usr/bin/diff"):
  302.           cmd = ["/usr/bin/diff", "-u", current, new]
  303.           diff = utf8(subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0])
  304.           self.confDialogue.textview_conffile.setText(diff)
  305.         else:
  306.           self.confDialogue.textview_conffile.setText(_("The 'diff' command was not found"))
  307.         result = self.confDialogue.exec_()
  308.         self.time_ui += time.time() - start
  309.         # if replace, send this to the terminal
  310.         if result == QDialog.Accepted:
  311.             os.write(self.master_fd, "y\n")
  312.         else:
  313.             os.write(self.master_fd, "n\n")
  314.  
  315.     def showConffile(self):
  316.         if self.confDialogue.textview_conffile.isVisible():
  317.             self.confDialogue.textview_conffile.hide()
  318.             self.confDialogue.show_difference_button.setText(_("Show Difference >>>"))
  319.         else:
  320.             self.confDialogue.textview_conffile.show()
  321.             self.confDialogue.show_difference_button.setText(_("<<< Hide Difference"))
  322.  
  323.     def fork(self):
  324.         """pty voodoo"""
  325.         (self.child_pid, self.master_fd) = pty.fork()
  326.         if self.child_pid == 0:
  327.             os.environ["TERM"] = "dumb"
  328.             if (not os.environ.has_key("DEBIAN_FRONTEND") or
  329.                 os.environ["DEBIAN_FRONTEND"] == "kde"):
  330.                 os.environ["DEBIAN_FRONTEND"] = "noninteractive"
  331.             os.environ["APT_LISTCHANGES_FRONTEND"] = "none"
  332.         logging.debug(" fork pid is: %s" % self.child_pid)
  333.         return self.child_pid
  334.  
  335.     def statusChange(self, pkg, percent, status):
  336.         """update progress bar and label"""
  337.         # start the timer when the first package changes its status
  338.         if self.start_time == 0.0:
  339.           #print "setting start time to %s" % self.start_time
  340.           self.start_time = time.time()
  341.         self.progress.setValue(self.percent)
  342.         self.label_status.setText(unicode(status.strip(), 'UTF-8'))
  343.         # start showing when we gathered some data
  344.         if percent > 1.0:
  345.           self.last_activity = time.time()
  346.           self.activity_timeout_reported = False
  347.           delta = self.last_activity - self.start_time
  348.           # time wasted in conffile questions (or other ui activity)
  349.           delta -= self.time_ui
  350.           time_per_percent = (float(delta)/percent)
  351.           eta = (100.0 - self.percent) * time_per_percent
  352.           # only show if we have some sensible data (60sec < eta < 2days)
  353.           if eta > 61.0 and eta < (60*60*24*2):
  354.             self.progress_text.setText(_("About %s remaining") % FuzzyTimeToStr(eta))
  355.           else:
  356.             self.progress_text.setText(" ")
  357.  
  358.     def finishUpdate(self):
  359.         self.label_status.setText("")
  360.  
  361.     def updateInterface(self):
  362.         """
  363.         no mainloop in this application, just call processEvents lots here
  364.         it's also important to sleep for a minimum amount of time
  365.         """
  366.         # log the output of dpkg (on the master_fd) to the terminal log
  367.         while True:
  368.             try:
  369.                 (rlist, wlist, xlist) = select.select([self.master_fd],[],[], 0)
  370.                 if len(rlist) > 0:
  371.                     line = os.read(self.master_fd, 255)
  372.                     self._terminal_log.write(line)
  373.                     self.parent.terminal_text.insertWithTermCodes(utf8(line))
  374.                 else:
  375.                     break
  376.             except Exception, e:
  377.                 print e
  378.                 logging.debug("error reading from self.master_fd '%s'" % e)
  379.                 break
  380.  
  381.         # now update the GUI
  382.         try:
  383.           InstallProgress.updateInterface(self)
  384.         except ValueError, e:
  385.           logging.error("got ValueError from InstallProgress.updateInterface. Line was '%s' (%s)" % (self.read, e))
  386.           # reset self.read so that it can continue reading and does not loop
  387.           self.read = ""
  388.         # check about terminal activity
  389.         if self.last_activity > 0 and \
  390.            (self.last_activity + self.TIMEOUT_TERMINAL_ACTIVITY) < time.time():
  391.           if not self.activity_timeout_reported:
  392.             #FIXME bug 95465, I can't recreate this, so here's a hacky fix
  393.             try:
  394.                 logging.warning("no activity on terminal for %s seconds (%s)" % (self.TIMEOUT_TERMINAL_ACTIVITY, self.label_status.text()))
  395.             except UnicodeEncodeError:
  396.                 logging.warning("no activity on terminal for %s seconds" % (self.TIMEOUT_TERMINAL_ACTIVITY))
  397.             self.activity_timeout_reported = True
  398.           self.parent.window_main.konsole_frame.show()
  399.         QApplication.processEvents()
  400.         time.sleep(0.02)
  401.  
  402.     def waitChild(self):
  403.         while True:
  404.             self.updateInterface()
  405.             (pid, res) = os.waitpid(self.child_pid,os.WNOHANG)
  406.             if pid == self.child_pid:
  407.                 break
  408.         return os.WEXITSTATUS(res)
  409.  
  410. # inherit from the class created in window_main.ui
  411. # to add the handler for closing the window
  412. class UpgraderMainWindow(QWidget):
  413.  
  414.     def __init__(self):
  415.         QWidget.__init__(self)
  416.         #uic.loadUi("window_main.ui", self)
  417.         loadUi("window_main.ui", self)
  418.  
  419.     def setParent(self, parentRef):
  420.         self.parent = parentRef
  421.  
  422.     def closeEvent(self, event):
  423.         close = self.parent.on_window_main_delete_event()
  424.         if close:
  425.             event.accept()
  426.         else:
  427.             event.ignore()
  428.  
  429. class DistUpgradeViewKDE(DistUpgradeView):
  430.     """KDE frontend of the distUpgrade tool"""
  431.     def __init__(self, datadir=None, logdir=None):
  432.         # silence the PyQt4 logger
  433.         logger = logging.getLogger("PyQt4")
  434.         logger.setLevel(logging.INFO)
  435.         if not datadir:
  436.           localedir=os.path.join(os.getcwd(),"mo")
  437.         else:
  438.           localedir="/usr/share/locale/update-manager"
  439.  
  440.         # FIXME: i18n must be somewhere relative do this dir
  441.         try:
  442.           gettext.bindtextdomain("update-manager", localedir)
  443.           gettext.textdomain("update-manager")
  444.         except Exception, e:
  445.           logging.warning("Error setting locales (%s)" % e)
  446.  
  447.         #about = KAboutData("adept_manager","Upgrader","0.1","Dist Upgrade Tool for Kubuntu",KAboutData.License_GPL,"(c) 2007 Canonical Ltd",
  448.         #"http://wiki.kubuntu.org/KubuntuUpdateManager", "jriddell@ubuntu.com")
  449.         #about.addAuthor("Jonathan Riddell", None,"jriddell@ubuntu.com")
  450.         #about.addAuthor("Michael Vogt", None,"michael.vogt@ubuntu.com")
  451.         #KCmdLineArgs.init(["./dist-upgrade.py"],about)
  452.  
  453.         #self.app = KApplication()
  454.         self.app = QApplication(["update-manager"])
  455.  
  456.         if os.path.exists("/usr/share/icons/oxygen/48x48/apps/system-software-update.png"):
  457.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/apps/system-software-update.png")
  458.         else:
  459.             messageIcon = QPixmap("/usr/share/icons/hicolor/48x48/apps/adept_manager.png")
  460.         self.app.setWindowIcon(QIcon(messageIcon))
  461.  
  462.         self.window_main = UpgraderMainWindow()
  463.         self.window_main.setParent(self)
  464.         self.window_main.show()
  465.  
  466.         self.prev_step = 0 # keep a record of the latest step
  467.  
  468.         self._opCacheProgress = KDEOpProgress(self.window_main.progressbar_cache, self.window_main.progress_text)
  469.         self._fetchProgress = KDEFetchProgressAdapter(self)
  470.         self._cdromProgress = KDECdromProgressAdapter(self)
  471.  
  472.         self._installProgress = KDEInstallProgressAdapter(self)
  473.  
  474.         # reasonable fault handler
  475.         sys.excepthook = self._handleException
  476.  
  477.         self.window_main.showTerminalButton.setEnabled(False)
  478.         self.app.connect(self.window_main.showTerminalButton, SIGNAL("clicked()"), self.showTerminal)
  479.  
  480.         #kdesu requires us to copy the xauthority file before it removes it when Adept is killed
  481.         copyXauth = tempfile.mktemp("", "adept")
  482.         if 'XAUTHORITY' in os.environ and os.environ['XAUTHORITY'] != copyXauth:
  483.             shutil.copy(os.environ['XAUTHORITY'], copyXauth)
  484.             os.environ["XAUTHORITY"] = copyXauth
  485.  
  486.         # Note that with kdesudo this needs --nonewdcop
  487.         ## create a new DCOP-Client:
  488.         #client = DCOPClient()
  489.         ## connect the client to the local DCOP-server:
  490.         #client.attach()
  491.  
  492.         #for qcstring_app in client.registeredApplications():
  493.         #    app = str(qcstring_app)
  494.         #    if app.startswith("adept"): 
  495.         #        adept = DCOPApp(qcstring_app, client)
  496.         #        adeptInterface = adept.object("MainApplication-Interface")
  497.         #        adeptInterface.quit()
  498.  
  499.         # This works just as well
  500.         subprocess.call(["killall", "adept_manager"])
  501.         subprocess.call(["killall", "adept_updater"])
  502.  
  503.         # init gettext
  504.         gettext.bindtextdomain("update-manager",localedir)
  505.         gettext.textdomain("update-manager")
  506.         self.translate_widget_children()
  507.         self.window_main.label_title.setText(self.window_main.label_title.text().replace("Ubuntu", "Kubuntu"))
  508.  
  509.         # setup terminal text in hidden by default spot
  510.         self.window_main.konsole_frame.hide()
  511.         self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame)
  512.         self.window_main.konsole_frame.setMinimumSize(600, 400)
  513.         self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame)
  514.         self.konsole_frame_layout.addWidget(self.terminal_text)
  515.         self.terminal_text.show()
  516.  
  517.         # for some reason we need to start the main loop to get everything displayed
  518.         # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets
  519.         QTimer.singleShot(10, self.exitMainLoop)
  520.         self.app.exec_()
  521.  
  522.     def exitMainLoop(self):
  523.         print "exitMainLoop"
  524.         self.app.exit()
  525.  
  526.     def translate_widget_children(self, parentWidget=None):
  527.         if parentWidget == None:
  528.             parentWidget = self.window_main
  529.         if isinstance(parentWidget, QDialog) or isinstance(parentWidget, QWidget):
  530.             if str(parentWidget.windowTitle()) == "Error":
  531.                 parentWidget.setWindowTitle( gettext.dgettext("kdelibs", "Error"))
  532.             else:
  533.                 parentWidget.setWindowTitle(_( str(parentWidget.windowTitle()) ))
  534.  
  535.         if parentWidget.children() != None:
  536.             for widget in parentWidget.children():
  537.                 self.translate_widget(widget)
  538.                 self.translate_widget_children(widget)
  539.  
  540.     def translate_widget(self, widget):
  541.         if isinstance(widget, QLabel) or isinstance(widget, QPushButton):
  542.             if str(widget.text()) == "&Cancel":
  543.                 widget.setText(unicode(gettext.dgettext("kdelibs", "&Cancel"), 'UTF-8'))
  544.             elif str(widget.text()) == "&Close":
  545.                 widget.setText(unicode(gettext.dgettext("kdelibs", "&Close"), 'UTF-8'))
  546.             elif str(widget.text()) != "":
  547.                 widget.setText( _(str(widget.text())).replace("_", "&") )
  548.  
  549.     def _handleException(self, exctype, excvalue, exctb):
  550.         """Crash handler."""
  551.  
  552.         if (issubclass(exctype, KeyboardInterrupt) or
  553.             issubclass(exctype, SystemExit)):
  554.             return
  555.  
  556.         # we handle the exception here, hand it to apport and run the
  557.         # apport gui manually after it because we kill u-m during the upgrade
  558.         # to prevent it from popping up for reboot notifications or FF restart
  559.         # notifications or somesuch
  560.         lines = traceback.format_exception(exctype, excvalue, exctb)
  561.         logging.error("not handled exception in KDE frontend:\n%s" % "\n".join(lines))
  562.         # we can't be sure that apport will run in the middle of a upgrade
  563.         # so we still show a error message here
  564.         apport_crash(exctype, excvalue, exctb)
  565.         if not run_apport():
  566.             tbtext = ''.join(traceback.format_exception(exctype, excvalue, exctb))
  567.             dialog = QDialog(self.window_main)
  568.             loadUi("dialog_error.ui", dialog)
  569.             self.translate_widget_children(self.dialog)
  570.             #FIXME make URL work
  571.             #dialog.connect(dialog.beastie_url, SIGNAL("leftClickedURL(const QString&)"), self.openURL)
  572.             dialog.crash_detail.setText(tbtext)
  573.             dialog.exec_()
  574.         sys.exit(1)
  575.  
  576.     def openURL(self, url):
  577.         """start konqueror"""
  578.         #need to run this else kdesu can't run Konqueror
  579.         #subprocess.call(['su', 'ubuntu', 'xhost', '+localhost'])
  580.         QDesktopServices.openUrl(QUrl(url))
  581.  
  582.     def reportBug(self):
  583.         """start konqueror"""
  584.         #need to run this else kdesu can't run Konqueror
  585.         #subprocess.call(['su', 'ubuntu', 'xhost', '+localhost'])
  586.         QDesktopServices.openUrl(QUrl("https://launchpad.net/ubuntu/+source/update-manager/+filebug"))
  587.  
  588.     def showTerminal(self):
  589.         if self.window_main.konsole_frame.isVisible():
  590.             self.window_main.konsole_frame.hide()
  591.             self.window_main.showTerminalButton.setText(_("Show Terminal >>>"))
  592.         else:
  593.             self.window_main.konsole_frame.show()
  594.             self.window_main.showTerminalButton.setText(_("<<< Hide Terminal"))
  595.         self.window_main.resize(self.window_main.sizeHint())
  596.  
  597.     def getFetchProgress(self):
  598.         return self._fetchProgress
  599.  
  600.     def getInstallProgress(self, cache):
  601.         self._installProgress._cache = cache
  602.         return self._installProgress
  603.  
  604.     def getOpCacheProgress(self):
  605.         return self._opCacheProgress
  606.  
  607.     def getCdromProgress(self):
  608.         return self._cdromProgress
  609.  
  610.     def updateStatus(self, msg):
  611.         self.window_main.label_status.setText(utf8(msg))
  612.  
  613.     def hideStep(self, step):
  614.         image = getattr(self.window_main,"image_step%i" % step)
  615.         label = getattr(self.window_main,"label_step%i" % step)
  616.         image.hide()
  617.         label.hide()
  618.  
  619.     def abort(self):
  620.         step = self.prev_step
  621.         if step > 0:
  622.             image = getattr(self.window_main,"image_step%i" % step)
  623.             if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
  624.                 cancelIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png")
  625.             elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
  626.                 cancelIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png")
  627.             else:
  628.                 cancelIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/cancel.png")
  629.             image.setPixmap(cancelIcon)
  630.             image.show()
  631.  
  632.     def setStep(self, step):
  633.         if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png"):
  634.             okIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png")
  635.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png"):
  636.             okIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png")
  637.         else:
  638.             okIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/ok.png")
  639.  
  640.         if os.path.exists("/usr/share/icons/oxygen/16x16/actions/arrow-right.png"):
  641.             arrowIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/arrow-right.png")
  642.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png"):
  643.             arrowIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png")
  644.         else:
  645.             arrowIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png")
  646.  
  647.         if self.prev_step:
  648.             image = getattr(self.window_main,"image_step%i" % self.prev_step)
  649.             label = getattr(self.window_main,"label_step%i" % self.prev_step)
  650.             image.setPixmap(okIcon)
  651.             image.show()
  652.             ##arrow.hide()
  653.         self.prev_step = step
  654.         # show the an arrow for the current step and make the label bold
  655.         image = getattr(self.window_main,"image_step%i" % step)
  656.         label = getattr(self.window_main,"label_step%i" % step)
  657.         image.setPixmap(arrowIcon)
  658.         image.show()
  659.         label.setText("<b>" + label.text() + "</b>")
  660.  
  661.     def information(self, summary, msg, extended_msg=None):
  662.         msg = "<big><b>%s</b></big><br />%s" % (summary,msg)
  663.  
  664.         dialogue = QDialog(self.window_main)
  665.         loadUi("dialog_error.ui", dialogue)
  666.         self.translate_widget_children(dialogue)
  667.         dialogue.label_error.setText(utf8(msg))
  668.         if extended_msg != None:
  669.             dialogue.textview_error.setText(utf8(extended_msg))
  670.             dialogue.textview_error.show()
  671.         else:
  672.             dialogue.textview_error.hide()
  673.         dialogue.button_bugreport.hide()
  674.         dialogue.setWindowTitle(_("Information"))
  675.  
  676.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-information.png"):
  677.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-information.png")
  678.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png"):
  679.             messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png")
  680.         else:
  681.             messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png")
  682.         dialogue.image.setPixmap(messageIcon)
  683.         dialogue.exec_()
  684.  
  685.     def error(self, summary, msg, extended_msg=None):
  686.         msg="<big><b>%s</b></big><br />%s" % (summary, msg)
  687.  
  688.         dialogue = QDialog(self.window_main)
  689.         loadUi("dialog_error.ui", dialogue)
  690.         self.translate_widget_children(dialogue)
  691.         dialogue.label_error.setText(utf8(msg))
  692.         if extended_msg != None:
  693.             dialogue.textview_error.setText(utf8(extended_msg))
  694.             dialogue.textview_error.show()
  695.         else:
  696.             dialogue.textview_error.hide()
  697.         dialogue.button_close.show()
  698.         self.app.connect(dialogue.button_bugreport, SIGNAL("clicked()"), self.reportBug)
  699.  
  700.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-error.png"):
  701.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-error.png")
  702.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png"):
  703.             messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png")
  704.         else:
  705.             messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png")
  706.         dialogue.image.setPixmap(messageIcon)
  707.         dialogue.exec_()
  708.  
  709.         return False
  710.  
  711.     def confirmChanges(self, summary, changes, downloadSize, 
  712.                        actions=None, removal_bold=True):
  713.         """show the changes dialogue"""
  714.         # FIXME: add a whitelist here for packages that we expect to be
  715.         # removed (how to calc this automatically?)
  716.         DistUpgradeView.confirmChanges(self, summary, changes, downloadSize)
  717.         msg = unicode(self.confirmChangesMessage, 'UTF-8')
  718.         self.changesDialogue = QDialog(self.window_main)
  719.         loadUi("dialog_changes.ui", self.changesDialogue)
  720.  
  721.         self.changesDialogue.treeview_details.hide()
  722.         self.changesDialogue.connect(self.changesDialogue.show_details_button, SIGNAL("clicked()"), self.showChangesDialogueDetails)
  723.         self.translate_widget_children(self.changesDialogue)
  724.         self.changesDialogue.show_details_button.setText(_("Details") + " >>>")
  725.         self.changesDialogue.resize(self.changesDialogue.sizeHint())
  726.  
  727.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-warning.png"):
  728.             warningIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-warning.png")
  729.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png"):
  730.             warningIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png")
  731.         else:
  732.             warningIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png")
  733.  
  734.         self.changesDialogue.question_pixmap.setPixmap(warningIcon)
  735.  
  736.         if actions != None:
  737.             cancel = actions[0].replace("_", "")
  738.             self.changesDialogue.button_cancel_changes.setText(cancel)
  739.             confirm = actions[1].replace("_", "")
  740.             self.changesDialogue.button_confirm_changes.setText(confirm)
  741.  
  742.         summaryText = unicode("<big><b>%s</b></big>" % summary, 'UTF-8')
  743.         self.changesDialogue.label_summary.setText(summaryText)
  744.         self.changesDialogue.label_changes.setText(msg)
  745.         # fill in the details
  746.         self.changesDialogue.treeview_details.clear()
  747.         self.changesDialogue.treeview_details.setHeaderLabels(["Packages"])
  748.         self.changesDialogue.treeview_details.header().hide()
  749.         for rm in self.toRemove:
  750.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove %s") % rm]) )
  751.         for inst in self.toInstall:
  752.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Install %s") % inst]) )
  753.         for up in self.toUpgrade:
  754.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Upgrade %s") % up]) )
  755.  
  756.         #FIXME resize label, stop it being shrinkable
  757.         res = self.changesDialogue.exec_()
  758.         if res == QDialog.Accepted:
  759.             return True
  760.         return False
  761.  
  762.     def showChangesDialogueDetails(self):
  763.         if self.changesDialogue.treeview_details.isVisible():
  764.             self.changesDialogue.treeview_details.hide()
  765.             self.changesDialogue.show_details_button.setText(_("Details") + " >>>")
  766.         else:
  767.             self.changesDialogue.treeview_details.show()
  768.             self.changesDialogue.show_details_button.setText("<<< " + _("Details"))
  769.         self.changesDialogue.resize(self.changesDialogue.sizeHint())
  770.  
  771.     def askYesNoQuestion(self, summary, msg, default='No'):
  772.         answer = QMessageBox.question(self.window_main, unicode(summary, 'UTF-8'), unicode("<font>") + unicode(msg, 'UTF-8'), QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
  773.         if answer == QMessageBox.Yes:
  774.             return True
  775.         return False
  776.  
  777.     def confirmRestart(self):
  778.         messageBox = QMessageBox(QMessageBox.Question, _("Restart required"), _("<b><big>Restart the system to complete the upgrade</big></b>"), QMessageBox.NoButton, self.window_main)
  779.         yesButton = messageBox.addButton(QMessageBox.Yes)
  780.         noButton = messageBox.addButton(QMessageBox.No)
  781.         yesButton.setText(_("_Restart Now").replace("_", "&"))
  782.         noButton.setText(gettext.dgettext("kdelibs", "&Close"))
  783.         answer = messageBox.exec_()
  784.         if answer == QMessageBox.Yes:
  785.             return True
  786.         return False
  787.  
  788.     def processEvents(self):
  789.         QApplication.processEvents()
  790.  
  791.     def on_window_main_delete_event(self):
  792.         #FIXME make this user friendly
  793.         text = _("""<b><big>Cancel the running upgrade?</big></b>
  794.  
  795. The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade.""")
  796.         text = text.replace("\n", "<br />")
  797.         cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"), text, QMessageBox.Yes, QMessageBox.No)
  798.         if cancel == QMessageBox.Yes:
  799.             return True
  800.         return False
  801.  
  802. if __name__ == "__main__":
  803.   
  804.   view = DistUpgradeViewKDE()
  805.   view.askYesNoQuestion("input box test","bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar ")
  806.  
  807.   if sys.argv[1] == "--test-term":
  808.       pid = view.terminal_text.fork()
  809.       if pid == 0:
  810.           subprocess.call(["bash"])
  811.           sys.exit()
  812.       while True:
  813.           view.terminal_text.updateInterface()
  814.           QApplication.processEvents()
  815.           time.sleep(0.01)
  816.  
  817.   if sys.argv[1] == "--show-in-terminal":
  818.       for c in open(sys.argv[2]).read():
  819.           view.terminal_text.insertWithTermCodes( c )
  820.           #print c, ord(c)
  821.           QApplication.processEvents()
  822.           time.sleep(0.05)
  823.       while True:
  824.           QApplication.processEvents()
  825.  
  826.   cache = apt.Cache()
  827.   for pkg in sys.argv[1:]:
  828.     if cache[pkg].isInstalled and not cache[pkg].isUpgradable: 
  829.       cache[pkg].markDelete(purge=True)
  830.     else:
  831.       cache[pkg].markInstall()
  832.   cache.commit(view._fetchProgress,view._installProgress)
  833.  
  834.   # keep the window open
  835.   while True:
  836.       QApplication.processEvents()
  837.